#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

// 管道管理：先描述再组织
class Channel
{
public:
    Channel(int wfd, int child_id)
        : _wfd(wfd), _child_id(child_id)
    {
        _name = "_WFD:" + std::to_string(_wfd) + "_CHILD_ID:" + std::to_string(_child_id);
    }

    ~Channel()
    {
    }

    int Getwfd() const
    {
        return _wfd;
    }

    int Getchild_id() const
    {
        return _child_id;
    }

    void CloseChannel()
    {
        close(_wfd);
    }

    void WaitchildProcess()
    {
        waitpid(_child_id, nullptr, 0);
    }


private:
    int _wfd;
    int _child_id;
    std::string _name;
};

class Channels_Manneger
{
public:
    Channels_Manneger(int num = 5)
        : _num(num)
    {
    }

    bool Work(int wfd, int childfd)
    {
        return true;
    }

    bool Insert()
    {
        for (int i = 0; i < _num; i++)
        {
            // 创建管道和子进程
            int pipefd[2] = {0};
            int n1;
            if (n1 < 0)
            {
                std::cerr << "创建管道出现错误!" << std::endl;
                return false;
            }

            int n2 = fork();
            if (n2 < 0)
            {
                std::cerr << "创建子进程出现错误!" << std::endl;
            }
            else if (n2 == 0)
            {
                // 子进程
                close(pipefd[1]);
                Work(_cm[i].Getwfd(), _cm[i].Getchild_id());
                close(pipefd[0]);
                exit(0);
            }
            else
            {
                // 父进程
                close(pipefd[0]);
                int tmp = waitpid(n2, nullptr, 0);
                (void)tmp;
                close(pipefd[1]);
            }
        }

        return true;
    }

    void Close()
    {
        for(auto& e : _cm)
        {
            e.CloseChannel();
        }
    }

    void Wait()
    {
        for(auto& e : _cm)
        {
            e.WaitchildProcess();
        }
    }

    ~Channels_Manneger()
    {
    }

private:
    std::vector<Channel> _cm;
    int _num;
};